/**
 * Created by PengWei on 2018/7/25.
 */

namespace mengdao {
    import Event = egret.Event;

    /**
     *  指令安装器
     *  当通过Context.mapper去绑定key和value时，
     *  key作为触发指令的事件名，value作为指令的BinderKey,
     *  在context接收到key事件时，执行指令的execute方法
     */
    export class CommandInstaller implements IExtension {
        private _context: Context;
        private _injector: Injector;

        public extend(context: Context): void {
            this._context = context;
            this._injector = context.injector;
            this._context.addEventListener(ContextEvent.BIND_MAP, this.onBindMap, this);
        }

        private onBindMap(e: ContextEvent): void {
            let data: ContextEventBindData = e.data as ContextEventBindData;
            let key = data.key;
            let value = data.value;

            if (typeof key === "string") {
                this.bindCommand(key, value, data);
            }
        }

        private bindCommand(key: string, value: any, data: ContextEventBindData): void {
            let callback = (e: Event) => {//ask 这个callback在被remove之前，此bindCommand方法占用的内存不能回收
                //创建一个新的Command来处理
                let command: BaseCommand = this._context.injector.getFromBind(value);
                command.fromContextExecute(this._context, e.type, e.data);

                if (data.once) {
                    this._context.removeEventListener(key, callback, this);
                    this._injector.unmap(key);
                }
            }

            this._context.addEventListener(key, callback, this);
        }
    }
}